import * as cloudDb from '@agconnect/database-server';
import { collect } from './model/collect';
import { resource } from './model/resource';
import * as agc from '@agconnect/common-server';
import * as Utils from './utils/Utils.js';

const ZONE_NAME = "HarmonyOSDeveloper";

export class DatabaseHelper {
  logger;
  cloudDbZone;

  constructor(context, logger) {
    this.logger = logger;
    const credential = Utils.getCredential(context, logger);
    try {
      // 初始化AGCClient
      logger.info("begin to init agcClient");
      let agcClient;
      try {
        agcClient = agc.AGCClient.getInstance();
      } catch {
        agc.AGCClient.initialize(credential);
        agcClient = agc.AGCClient.getInstance();
      }
      // 初始化AGConnectCloudDB实例
      logger.info("begin to init cloudDb");
      let cloudDbInstance;
      try {
        cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
      } catch {
        cloudDb.AGConnectCloudDB.initialize(agcClient);
        cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
      }
      // 创建CloudDBZoneConfig配置对象，并设置云侧CloudDB zone名称，打开Cloud DB zone实例
      const cloudDBZoneConfig = new cloudDb.CloudDBZoneConfig(ZONE_NAME);
      this.cloudDbZone = cloudDbInstance.openCloudDBZone(cloudDBZoneConfig);
    } catch (err) {
      logger.error("init CloudDBZoneWrapper error: " + err);
    }
  }

  async insertCollect(userid, resourceId) {
    if (!this.cloudDbZone) {
      console.log("CloudDBClient is null, try re-initialize it");
      return;
    }
    try {
      let collectObj = new collect();
      collectObj.setResource_id(resourceId);
      collectObj.setUser_id(userid)
      collectObj.setId(userid + resourceId)
      collectObj.setCollect_time(new Date())
      const resp = await this.cloudDbZone.executeUpsert(collectObj);
      this.logger.info("insert topic success ");
      console.log('resp=>', resp);
      this.updateCollectedCount(resourceId, 1)
      return resp;
    }
    catch (error) {
      this.logger.info("insert topic error " + error);
      return undefined
    }
  }

  async deleteCollect(userid, resourceId) {
    if (!this.cloudDbZone) {
      console.log("CloudDBClient is null, try re-initialize it");
      return;
    }
    try {
      const cloudDBZoneQuery = cloudDb.CloudDBZoneQuery.where(collect);
      cloudDBZoneQuery.equalTo("user_id", userid)
      cloudDBZoneQuery.equalTo("resource_id", resourceId)
      const resp1 = await this.cloudDbZone.executeQuery(cloudDBZoneQuery);
      console.log('resp1=>', resp1);
      let collectData = resp1.getSnapshotObjects();
      if (collectData.length > 0) {
        this.updateCollectedCount(resourceId, -1)
      }
      const resp2 = await this.cloudDbZone.executeDelete(collectData);
      this.logger.info("delete topic success ");
      console.log('resp=>', resp2);
      return resp2;
    } catch (error) {
      this.logger.info("delete topic error " + error);
      return undefined
    }
  }

  async updateCollectedCount(resourceId, addCount) {
    if (!this.cloudDbZone) {
      console.log("CloudDBClient is null, try re-initialize it");
      return;
    }
    try {
      const resourceQuery = cloudDb.CloudDBZoneQuery.where(resource);
      resourceQuery.equalTo("id", resourceId)
      const resourceResp = await this.cloudDbZone.executeQuery(resourceQuery);
      console.log('resourceResp=>', resourceResp);
      let resourceData = resourceResp.getSnapshotObjects();
      if (resourceData.length > 0) {
        let updateResource: resource = resourceData[0]
        const operator = cloudDb.CloudDBZoneObjectOperator.build(updateResource).increment('collect_count', addCount);
        const resp = await this.cloudDbZone.executeUpdate(operator);
        this.logger.info("update resource success ");
        console.log('resp=>', resp);
      }
    }
    catch (error) {
      this.logger.info("update resource error " + error);
    }
  }
}